package cn.vivi.seckill.rabbitmq;


import cn.vivi.seckill.pojo.SecKillMessage;
import cn.vivi.seckill.pojo.SeckillGoods;
import cn.vivi.seckill.pojo.SeckillOrder;
import cn.vivi.seckill.pojo.User;
import cn.vivi.seckill.service.OrderService;
import cn.vivi.seckill.service.SecKillGoodsService;
import cn.vivi.seckill.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
@Slf4j
public class MQReceiver {

    @Autowired
    private SecKillGoodsService secKillGoodsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderService orderService;

    @RabbitListener(queues = "seckillQueue")
    public void receiveSecKillMessage(String message) {
        log.info("接收的消息：{}", message);
        SecKillMessage secKillMessage = JsonUtils.toObj(message, SecKillMessage.class);

        User user = secKillMessage.getUser();
        String goodsId = secKillMessage.getGoodsId();
        SeckillGoods seckillGoods = secKillGoodsService.findByGoodsId(goodsId);
        // 库存不足
        if (seckillGoods.getStockCount() < 1) {
            return;
        }

        // 判断是否重复抢购
        // 重复抢购
        SeckillOrder seckillOrder = (SeckillOrder) redisTemplate.opsForValue().get("order:" + user.getPhone() + ":" + goodsId);
        if (!Objects.isNull(seckillOrder)) {
            return;
        }

        // 下订单
        orderService.toSecKill(goodsId, "", user);
    }

}
